
package vv.lines.view.swing;

import vv.lines.core.IActionHandler;
import vv.lines.view.FieldItemView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;

import static vv.lines.core.ActionId.SELECTION;

/**
 *
 * @author vpotapenko
 */
public abstract class SwingFieldItem implements FieldItemView {

    private IActionHandler handler;

    private Rectangle rectangle = new Rectangle();
    private boolean visible;
    private int zOrder = 0;

    private SwingFieldComponent owner;

    private boolean dirty;

    public void setHandler(IActionHandler handler) {
        this.handler = handler;
    }

    public void setSize(int width, int height) {
        Rectangle rectangle = new Rectangle(this.rectangle);
        this.rectangle.setSize(width, height);

        if (owner != null) owner.handleDirty(rectangle, this.rectangle);
    }

    public int getWidth() {
        return rectangle.width;
    }

    public int getHeight() {
        return rectangle.height;
    }

    public void setLocation(int x, int y) {
        Rectangle oldRect = new Rectangle(rectangle);

        rectangle.setLocation(x, y);

        if (owner != null) owner.handleDirty(oldRect, rectangle);
    }

    public int getX() {
        return rectangle.x;
    }

    public int getY() {
        return rectangle.y;
    }

    public void setVisible(boolean visible) {
        this.visible = visible;
    }

    public SwingFieldComponent getOwner() {
        return owner;
    }

    public void setOwner(SwingFieldComponent owner) {
        this.owner = owner;
    }

    public void repaint() {
        JComponent parent = getOwner();
        if (parent != null) {
            parent.repaint();
        }
    }

    public void paint(Graphics g) {
        if (visible) paintObject(g);
    }

    protected abstract void paintObject(Graphics g);

    public int getZOrder() {
        return zOrder;
    }

    public void setZOrder(int zOrder) {
        this.zOrder = zOrder;
    }

    public Rectangle getBounds() {
        return getBounds(null);
    }

    public Rectangle getBounds(Rectangle rect) {
        if (rect == null) rect = new Rectangle();

        rect.setBounds(this.rectangle);
        return rect;
    }

    public boolean isDirty() {
        return dirty;
    }

    public void setDirty(boolean dirty) {
        this.dirty = dirty;
    }

    void onMouseClick(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)) {
            handler.handleAction(SELECTION);
        }
    }
}
